package com.feizhoutuobang.shapeline.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Calendar {

	public static final String INVALID_TIME = "1970-01-01 00:00:00.000";
	
	private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss.SSS";
	private static SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);

	public static String format(Date date) {
		return dateFormat.format(date);
	}
	
	public static String format(Date date, String format) {
		SimpleDateFormat dateFormat = new SimpleDateFormat(format);
		return dateFormat.format(date);
	}
	
	public static Date parse(String source) {
		try {
			return dateFormat.parse(source);
		} catch (ParseException e) {
			return null;
		}
	}

	public static Date now() {
		return new Date();
	}
	
	public static Date today() {
		java.util.Calendar ca = java.util.Calendar.getInstance();
		int hour = ca.get(java.util.Calendar.HOUR_OF_DAY);
		int minute = ca.get(java.util.Calendar.MINUTE);
		int second = ca.get(java.util.Calendar.SECOND);
		int millisecond = ca.get(java.util.Calendar.MILLISECOND);
		
		ca.add(java.util.Calendar.HOUR_OF_DAY, -hour);
		ca.add(java.util.Calendar.MINUTE, -minute);
		ca.add(java.util.Calendar.SECOND, -second);
		ca.add(java.util.Calendar.MILLISECOND, -millisecond);
		
		//long time = ca.getTimeInMillis() - (((hour * 60) + minute) * 60 + second) - millisecond;
		return ca.getTime();
	}
	
	public static Date invalidTime() {
		return parse(INVALID_TIME);
	}
	
	public static Date addSeconds(Date date, int seconds) {
		java.util.Calendar ca = java.util.Calendar.getInstance();
		ca.setTime(date);
		ca.add(java.util.Calendar.SECOND, seconds);
		return ca.getTime();
	}
}
